package com.bullsora.kindlerss.controller

import com.bullsora.kindlerss.model.AppUser

/**
 * 
 * @author Sorin Buliarca
 */
class MyProfileController {

  static defaultAction = "show"
  
  def show() {
    [currentUser : getAuthenticatedUser()]  
  }
  
  def edit() {
    AppUser currentUser = getAuthenticatedUser()
    def myProfile = new MyProfileCommand(kindleAccount: currentUser.kindleAccount,
                                         timeZone: currentUser.timeZone)
    [myProfile : myProfile, availableTimeZones : getAvailableTimeZones()]  
  }

  def update(MyProfileCommand myProfile) {
    if (myProfile.hasErrors()) {
      render(view: 'edit', model: [myProfile: myProfile, availableTimeZones: getAvailableTimeZones()])
      return
    }
    AppUser currentUser = getAuthenticatedUser()
    currentUser.kindleAccount = myProfile.kindleAccount
    currentUser.timeZone = myProfile.timeZone
    currentUser.save(flush: true)
    redirect(action : 'show')
  }

  private def getAvailableTimeZones() {
    AppUser currentUser = getAuthenticatedUser()
    def availableTimeZones = TimeZone.availableIDs.toList()
    if (currentUser.timeZone && !availableTimeZones.contains(currentUser.timeZone)) {
      availableTimeZones += currentUser.timeZone
    }
    return availableTimeZones.sort()
  }
}
